package com.student.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JdbcUtils2 {
	//定义属性
		private static String DRIVER_NAME = "com.mysql.cj.jdbc.Driver";
		private static String URL = "jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=CTT";
		private static String USER = "root";
		private static String PASSWORD = "123456";
		//jdbc双重检查锁来创建单例模式
		private static JdbcUtils2 instance = null;
		private JdbcUtils2() {
			
		}
		private static class HodlerClass {
			private static JdbcUtils2 instance = new JdbcUtils2();
		}
		public static JdbcUtils2 getInstance() {
			/*if (instance == null) {
				synchronized (JdbcUtils2.class) {
					if (instance == null) {
						instance = new JdbcUtils2();
					}
				}
			}*/
			return instance;
		}
		//加载驱动
		static {
			try {
				Class.forName(DRIVER_NAME);
			} catch (ClassNotFoundException e) {
				throw new ExceptionInInitializerError(e);
			}
		}
		
		//获取链接
		public static Connection getConnection() throws SQLException {
			return DriverManager.getConnection(URL, USER, PASSWORD);
		}
		//释放资源
		public static void free(ResultSet resultSet,Statement statement, Connection connection) {
			try {
				if (resultSet != null ) {
					resultSet.close();	
				}
			}catch (Exception e) {
				e.printStackTrace();
			}finally {
				try {
					if (statement != null) {
						statement.close();
					}
				}catch (Exception e) {
					e.printStackTrace();
				}finally {
					if (connection != null) {
						try {
							connection.close();
						} catch (SQLException e) {
							e.printStackTrace();
						}
					}	
				}
			}
		}
}
